<template>
  <div class="mod-prod-info">
    <div class="goback"><i class="el-icon-close" @click="goBack"></i></div>
    <el-form :model="dataForm" ref="dataForm" label-width="120px" :hide-required-asterisk='true'>
      <el-form-item label="产品图片" class="required">
        <mul-pic-upload v-model="dataForm.imgs" />
      </el-form-item>
      <el-form-item label="状态" class="required">
        <el-radio-group v-model="dataForm.status">
          <el-radio :label="1">上架</el-radio>
          <el-radio :label="0">下架</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="仅支持自提" class="required">
        <el-radio-group v-model="dataForm.isOnlySelfmention">
          <el-radio :label="'0'">是</el-radio>
          <el-radio :label="'1'">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="产品分类" class="required">
        <el-col :span="8">
          <el-select v-model="dataForm.categoryList" multiple placeholder="请选择" size='big'>
            <el-option v-for="item in category.list" :key="item.categoryId" :label="item.categoryName"
              :value="item.categoryId">
            </el-option>
          </el-select>
        </el-col>


      </el-form-item>
      <!-- <el-form-item label="产品分组">
        <el-col :span="8">
          <el-select v-model="dataForm.tagList"
                    multiple
                    style="width: 250px"
                    placeholder="请选择">
            <el-option v-for="item in this.tags"
                      :key="item.id"
                      :label="item.title"
                      :value="item.id">
            </el-option>
          </el-select>
        </el-col>
      </el-form-item> -->
      <el-form-item label="产品名称" prop="prodName" :rules="[{ required: true, message: '产品名称不能为空'}]" class="required">
        <el-col :span="8">
          <el-input v-model="dataForm.prodName" placeholder="产品名称" maxlength="50"></el-input>
        </el-col>
      </el-form-item>
      <el-form-item label="产品编码" prop="" class="required">
        <el-col :span="8">
          <el-input v-model="dataForm.barCode" placeholder="产品名称" maxlength="50"></el-input>
        </el-col>
      </el-form-item>
      <el-form-item label="产品卖点" prop="brief">
        <el-col :span="8">
          <el-input v-model="dataForm.brief" type="textarea" :autosize="{minRows: 2, maxRows: 4}" placeholder="产品卖点">
          </el-input>
        </el-col>
      </el-form-item>
      <!-- <el-form-item label="配送方式">
       <el-checkbox v-model="dataForm.deliveryMode.hasShopDelivery">商家配送</el-checkbox>
       <el-checkbox v-model="dataForm.deliveryMode.hasUserPickUp" checked>用户自提</el-checkbox>
     </el-form-item> -->
      <!-- <prod-transport v-show="dataForm.deliveryMode.hasShopDelivery"
                      v-model="dataForm.deliveryTemplateId"></prod-transport> -->
      <!-- <sku-tag ref="skuTag"
               @change="skuTagChangeSkuHandler"></sku-tag> -->
      <!-- <div class="prod-sku-tit">产品规格</div>
      <sku-table ref="skuTable"
                 v-model="dataForm.skuList"
                 :prodName.sync="dataForm.prodName"></sku-table> -->

      <el-form-item label="现价" class="required">
        <el-input v-model="dataForm.price"></el-input>
      </el-form-item>
      <el-form-item label="原价" class="required">
        <el-input v-model="dataForm.oriPrice"></el-input>
      </el-form-item>
      <el-form-item label="会员折扣" class="required">
        <el-input v-model="dataForm.vipDiscount"><template slot="append">%</template></el-input>
      </el-form-item>
      <el-form-item label="库存" class="required">
        <el-input v-model="dataForm.totalStocks"></el-input>
      </el-form-item>
      <el-form-item label="计量单位">
        <el-select v-model="dataForm.unit" filterable allow-create default-first-option placeholder="请选择计量单位">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="商品重量(g)">
        <el-input v-model="dataForm.weight"></el-input>
      </el-form-item>
      <el-form-item label="保质期">
        <el-input v-model="dataForm.qualitTime"></el-input>
        <el-radio v-model="dataForm.qualitTimeType" :label="1" border>天</el-radio>
        <el-radio v-model="dataForm.qualitTimeType" :label="2" border>月</el-radio>
      </el-form-item>
      <el-form-item label="产品详情" prop="content">
        <tiny-mce v-model="dataForm.content" ref="content" style="width:1000px"></tiny-mce>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
  import {
    treeDataTranslate,
    idList
  } from '@/utils'
  import MulPicUpload from '@/components/mul-pic-upload'
  import ProdTransport from './prod-transport'
  import SkuTag from './sku-tag'
  import SkuTable from './sku-table'
  import TinyMce from '@/components/tiny-mce'

  export default {
    data() {
      return {
        // 分类树展示与回显
        category: {
          list: [],
          selected: [],
          props: {
            value: 'categoryId',
            label: 'categoryName'
          }
        },
        options: [{
          value: '件',
          label: '件'
        }, {
          value: '袋',
          label: '袋'
        }, {
          value: '份',
          label: '份'
        }, {
          value: '瓶',
          label: '瓶'
        }, {
          value: '包',
          label: '包'
        }, {
          value: '盒',
          label: '盒'
        }, {
          value: '斤',
          label: '斤'
        },],
        // 规格列表
        dataForm: {
          prodName: '',
          brief: '',
          pic: '',
          imgs: '',
          barCode: '',
          price: 0,
          oriPrice: 0,
          vipDiscount: 0,
          totalStocks: 0,
          weight: 0,
          categoryList: [],
          prodId: 0,
          skuList: [{}],
          qualitTime: 0,
          qualitTimeType: 1,
          tagList: [],
          content: '',
          status: 1,
          unit: '',
          // isSpread:1,
          isOnlySelfmention: '1',
          deliveryMode: {
            hasShopDelivery: false,
            hasUserPickUp: false
          },
          deliveryTemplateId: null
        },
        tags: [],
        resourcesUrl: window.SITE_CONFIG.resourcesUrl
      }
    },
    components: {
      MulPicUpload,
      ProdTransport,
      TinyMce,
      SkuTag,
      SkuTable
    },
    computed: {
      defalutSku() {
        return this.$store.state.prod.defalutSku
      }
    },
    activated() {
      this.dataForm.prodId = this.$route.query.prodId
      this.getDataList()
    },
    methods: {
      // 获取分类数据
      getDataList() {
        // this.getTagList()
        this.getCategoryList().then(() => {
          // console.log(this.dataForm.prodId);
          if (this.dataForm.prodId) {
            // 获取产品数据
            this.$http({
              url: this.$http.adornUrl(`/prod/prod/info/${this.dataForm.prodId}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({
              data
            }) => {
              console.log(data);
              this.dataForm = Object.assign(this.dataForm, data)
              console.log(this.dataForm);
              // this.dataForm.weight = 0
              this.dataForm.weight = data.skuList[0].weight
              let categoryList = data.categoryList
              this.dataForm.categoryList = []
              categoryList.forEach(item => {
                this.dataForm.categoryList.push(item.categoryId)
              });
              // this.dataForm.deliveryMode = JSON.parse(data.deliveryMode)
              // this.$refs.skuTag.init(data.skuList)

              // this.$refs.skuTable.init()

              // this.category.selected = idList(this.category.list, this.dataForm.categoryId, 'categoryId', 'children').reverse()
              // this.dataForm.tagList = data.tagList
            })
          } else {
            this.$nextTick(() => {
              this.$refs['dataForm'].resetFields()
              // this.$refs.skuTag.init()
              this.dataForm.pic = ''
              this.dataForm.imgs = ''
            })
          }
        })
      },
      // 获取分类信息
      getCategoryList() {
        return this.$http({
          url: this.$http.adornUrl('/prod/category/listCategory'),
          method: 'get',
          params: this.$http.adornParams({
            saleType: 2  //1: 线上 2：线下
          })
        }).then(({
          data
        }) => {
          this.category.list = treeDataTranslate(data, 'categoryId', 'parentId')
          console.log(this.category);
        })
      },

      // 选择分类改变事件
      // handleCategoryChange (val) {
      //   this.dataForm.categoryId = val[val.length - 1]
      // },
      // 表单提交
      dataFormSubmit() {
        // console.log();
        this.$refs['dataForm'].validate((valid) => {
          if (!valid) {
            this.errorMsg('请填写产品名称')
            return
          }
          if (!this.dataForm.imgs) {
            this.errorMsg('请选择图片上传')
            return
          }
          if (this.dataForm.categoryList.length == 0) {
            this.errorMsg('请选择产品分类')
            return
          }
          // if (!this.dataForm.deliveryMode) {
          //   this.errorMsg('请选择配送方式')
          //   return
          // }
          // if (this.dataForm.deliveryMode.hasShopDelivery && !this.dataForm.deliveryTemplateId) {
          //   this.errorMsg('请选择运费模板')
          //   return
          // }
          let param = Object.assign({saleType: 2}, this.dataForm)
          // param.categoryList = JSON.stringify(param.categoryList)
          // 设置价格和库存
          // this.paramSetPriceAndStocks(param)

          if (param.price == 0) {
            this.errorMsg('请填写销售价格')
            return
          }
          if (param.totalStocks == 0 && param.status == 1) {
            this.errorMsg('请填写当前商品库存，或将商品状态改为下架')
            return
          }
          console.log(param)
          param.skuList[0].oriPrice = param.oriPrice
          param.skuList[0].price = param.price
          param.skuList[0].stocks = param.totalStocks
          param.skuList[0].weight = param.weight
          param.skuList[0].status = 1
          param.skuList[0].prodName = param.prodName
          param.skuList[0].barCode = param.barCode
          param.skuList[0].qualitTime = param.qualitTime
          param.skuList[0].qualitTimeType = param.qualitTimeType
          param.skuList[0].unit = param.unit
          param.skuList[0].saleType = 2 //1: 线上销售 2：线下销售
          // param.deliveryMode = undefined
          // param.deliveryModeVo = this.dataForm.deliveryMode
          // 商品主图
          param.pic = this.dataForm.imgs.split(',')[0]
          this.$http({
            url: this.$http.adornUrl(`/prod/prod`),
            method: param.prodId ? 'put' : 'post',
            data: this.$http.adornData(param)
          }).then(({ data }) => {
            console.log(data)
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.$store.commit('common/removeMainActiveTab')
                this.$router.push({
                  name: 'prod-prodList-offLine'
                })
                this.$emit('refreshDataList')
              }
            })
          })
        })
      },
      paramSetPriceAndStocks(param) {
        // 获取规格属性信息
        // param.skuList = this.$refs.prodSpec.getTableSpecData()
        // 商品库存
        param.totalStocks = 0
        // 商品价格
        param.price = 0
        // 商品原价
        param.oriPrice = 0
        // 商品实际库存
        for (let i = 0; i < param.skuList.length; i++) {
          const element = param.skuList[i]
          if (element.status !== 1) {
            continue
          }
          if (param.price === 0) {
            param.price = element.price ? Number.parseFloat(element.price) : 0
            param.oriPrice = element.oriPrice ? Number.parseFloat(element.oriPrice) : 0
          }
          // 商品价格为最低价的那件商品的价格
          param.price = Math.min(param.price, element.price)
          param.oriPrice = Math.min(param.oriPrice, element.oriPrice)
          if (param.price === element.price) {
            param.oriPrice = element.oriPrice ? Number.parseFloat(element.oriPrice) : 0
          }
          param.totalStocks += element.stocks ? Number.parseInt(element.stocks) : 0
        }
        // 如果sku没有商品名称，则使用商品的商品名称
        if (param.skuList.length === 1) {
          param.skuList[0].prodName = this.dataForm.prodName
        }
      },
      // skuTagChangeSkuHandler (skuList) {
      //   const prodName = this.dataForm.prodName
      //   skuList.forEach(sku => {
      //     if (sku.properties) {
      //       sku.skuName = ''
      //       let properties = sku.properties.split(';')
      //       for (const propertiesKey in properties) {
      //         sku.skuName += properties[propertiesKey].split(':')[1] + ' '
      //       }
      //       sku.prodName = prodName + ' ' + sku.skuName
      //     }
      //   })
      //   this.dataForm.skuList = skuList
      // },
      errorMsg(message) {
        this.$message({
          message: message,
          type: 'error',
          duration: 2000
        })
      },
      // 获取所有的分组信息
      // getTagList () {
      // this.$http({
      //   url: this.$http.adornUrl('/prod/prodTag/listTagList'),
      //   method: 'get',
      //   params: this.$http.adornParams()
      // }).then(({ data }) => {
      //   this.tags = data
      //   console.log(data);
      // })
      // },

      goBack() {
        history.go(-1)
      }
    }
  }
</script>
<style scoped>
  .goback {
    font-size: 30px;
    position: absolute;
    right: 20px;
    top: 20px;
    z-index: 1000;
  }

  .prod-sku-tit {
    margin-left: 30px;
  }

  .el-input {
    width: 300px;
  }

  .mod-prod-info .required>>>.el-form-item__label::before {
    content: "*";
    color: #F56C6C;
    margin-right: 5px;

  }
</style>
